package com.xiaoh.dormitoryrepairreportbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoh.dormitoryrepairreportbackend.common.BaseResponse;
import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.category.RepairCategoryAddRequest;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.category.RepairCategoryQueryRequest;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.category.RepairCategoryUpdateRequest;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.common.PageResponse;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.common.UpdateRequest;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.RepairCategory;
import com.xiaoh.dormitoryrepairreportbackend.service.RepairCategoryService;
import com.xiaoh.dormitoryrepairreportbackend.annotation.RequireRole;
import com.xiaoh.dormitoryrepairreportbackend.constant.UserConstant;
import com.xiaoh.dormitoryrepairreportbackend.utils.QueryUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 维修类别接口
 */
@RestController
@RequestMapping("/category")
@Slf4j
@Tag(name = "维修类别管理", description = "维修类别相关接口")
public class RepairCategoryController {

    @Resource
    private RepairCategoryService repairCategoryService;

    /**
     * 创建维修类别
     */
    @PostMapping("/add")
    @Operation(summary = "创建维修类别", description = "创建维修类别接口")
    @RequireRole(UserConstant.UserType.ADMIN)
    public BaseResponse<Long> addRepairCategory(@Valid @RequestBody RepairCategoryAddRequest categoryAddRequest, HttpServletRequest request) {
        if (categoryAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        RepairCategory repairCategory = new RepairCategory();
        BeanUtils.copyProperties(categoryAddRequest, repairCategory);

        boolean result = repairCategoryService.save(repairCategory);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return BaseResponse.success(repairCategory.getId().longValue());
    }

    /**
     * 更新维修类别
     */
    @PostMapping("/update")
    @Operation(summary = "更新维修类别", description = "更新维修类别接口")
    @RequireRole(UserConstant.UserType.ADMIN)
    public BaseResponse<Boolean> updateRepairCategory(@Valid @RequestBody RepairCategoryUpdateRequest categoryUpdateRequest, HttpServletRequest request) {
        if (categoryUpdateRequest == null || categoryUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Integer id = categoryUpdateRequest.getId();
        // 校验数据是否存在
        RepairCategory oldCategory = repairCategoryService.getById(id);
        if (oldCategory == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        RepairCategory repairCategory = new RepairCategory();
        BeanUtils.copyProperties(categoryUpdateRequest, repairCategory);

        boolean result = repairCategoryService.updateById(repairCategory);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return BaseResponse.success(true);
    }

    /**
     * 删除维修类别
     */
    @PostMapping("/delete")
    @Operation(summary = "删除维修类别", description = "删除维修类别接口")
    @RequireRole(UserConstant.UserType.ADMIN)
    public BaseResponse<Boolean> deleteRepairCategory(@Valid @RequestBody UpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = updateRequest.getId();
        // 校验数据是否存在
        RepairCategory oldCategory = repairCategoryService.getById(id);
        if (oldCategory == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = repairCategoryService.removeById(id);
        return BaseResponse.success(b);
    }

    /**
     * 根据 id 获取维修类别
     */
    @PostMapping("/get")
    @Operation(summary = "根据id获取维修类别", description = "根据id获取维修类别")
    public BaseResponse<RepairCategory> getRepairCategoryById(@Valid @RequestBody UpdateRequest getRequest) {
        if (getRequest == null || getRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = getRequest.getId();
        RepairCategory repairCategory = repairCategoryService.getById(id);
        if (repairCategory == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return BaseResponse.success(repairCategory);
    }

    /**
     * 分页获取维修类别列表
     * 使用游标分页保持性能，同时返回完整分页信息
     */
    @PostMapping("/list/page")
    @Operation(summary = "分页获取维修类别列表", description = "使用游标分页获取维修类别列表，返回完整分页信息（总记录数、总页数等）")
    public BaseResponse<PageResponse<RepairCategory>> listRepairCategoryByPage(@RequestBody RepairCategoryQueryRequest categoryQueryRequest) {
        if (categoryQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        QueryWrapper<RepairCategory> queryWrapper = new QueryWrapper<>();

        // 添加查询条件
        QueryUtils.addLikeCondition(queryWrapper, "category_name", categoryQueryRequest.getCategoryName());
        QueryUtils.addEqCondition(queryWrapper, "is_active", categoryQueryRequest.getIsActive());

        // 查询总记录数（不包含分页条件）
        QueryWrapper<RepairCategory> countWrapper = QueryUtils.createCountQueryWrapper(queryWrapper);
        Long total = repairCategoryService.count(countWrapper);

        // 添加游标分页
        QueryUtils.addCursorPagination(queryWrapper, categoryQueryRequest.getLastId(), categoryQueryRequest.getPageSize());

        // 查询维修类别列表
        List<RepairCategory> categoryList = repairCategoryService.list(queryWrapper);

        // 获取下一页游标
        Long nextCursor = QueryUtils.getNextCursor(categoryList);

        // 计算当前页码
        Long current = QueryUtils.calculateCurrentPage(categoryQueryRequest.getLastId(), categoryQueryRequest.getPageSize(), total);

        // 构建分页响应
        PageResponse<RepairCategory> pageResponse = PageResponse.of(categoryList, current, categoryQueryRequest.getPageSize().longValue(), total, nextCursor);
        return BaseResponse.success(pageResponse);
    }

    /**
     * 获取所有启用的维修类别
     */
    @PostMapping("/list/active")
    @Operation(summary = "获取所有启用的维修类别", description = "获取所有启用的维修类别")
    public BaseResponse<List<RepairCategory>> listActiveRepairCategory() {
        QueryWrapper<RepairCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_active", 1);
        queryWrapper.orderByAsc("id");
        
        List<RepairCategory> categoryList = repairCategoryService.list(queryWrapper);
        return BaseResponse.success(categoryList);
    }
}
